// 阿拉伯数字转中文数字
function NoToChinese(num) {
  if (num === '' || num === null || isNaN(num)) {
    return ''
  }
  // var AA = new Array('零', '一', '二', '三', '四', '五', '六', '七', '八', '九')
  // var BB = new Array('', '十', '百', '千', '万', '亿', '点', '')
  const AA = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']
  const BB = ['', '十', '百', '千', '万', '亿', '点', '']
  var a = ('' + num).replace(/(^0*)/g, '').split('.')
  var k = 0
  var re = ''
  for (var i = a[0].length - 1; i >= 0; i--) {
    switch (k) {
      case 0:
        re = BB[7] + re
        break
      case 4:
        if (!new RegExp('0{4}\\d{' + (a[0].length - i - 1) + '}$').test(a[0])) re = BB[4] + re
        break
      case 8:
        re = BB[5] + re
        BB[7] = BB[5]
        k = 0
        break
    }
    if (k % 4 == 2 && a[0].charAt(i + 2) != 0 && a[0].charAt(i + 1) == 0) re = AA[0] + re
    if (a[0].charAt(i) != 0) re = AA[a[0].charAt(i)] + BB[k % 4] + re
    k++
  }
  if (a.length > 1) {
    // 加上小数部分(如果有小数部分)
    re += BB[6]
    for (let i = 0; i < a[1].length; i++) re += AA[a[1].charAt(i)]
  }
  return re
}
function toParams(obj) {
  const arr = []
  for (const key in obj) {
    arr.push(`${key}=${obj[key]}`)
  }
  return '?' + arr.join('&')
}
/* 金额大写 */
function convertCurrency(money) {
  // 汉字的数字
  // const cnNums = new Array('零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖')
  const cnNums = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']
  // 基本单位
  // const cnIntRadice = new Array('', '拾', '佰', '仟')
  const cnIntRadice = ['', '拾', '佰', '仟']
  // 对应整数部分扩展单位
  const cnIntUnits = ['', '万', '亿', '兆']
  // 对应小数部分单位
  const cnDecUnits = ['角', '分', '毫', '厘']
  // 整数金额时后面跟的字符
  const cnInteger = '整'
  // 整型完以后的单位
  const cnIntLast = '元'
  // 最大处理的数字
  const maxNum = 999999999999999.9999
  // 金额整数部分
  let integerNum
  // 金额小数部分
  let decimalNum
  // 输出的中文金额字符串
  let chineseStr = ''
  // 分离金额后用的数组，预定义
  let parts
  if (money == '') {
    return ''
  }
  money = parseFloat(money)
  if (money >= maxNum) {
    // 超出最大处理数字
    return ''
  }
  if (money == 0) {
    chineseStr = cnNums[0] + cnIntLast + cnInteger
    return chineseStr
  }
  // 转换为字符串
  money = money.toString()
  if (money.indexOf('.') == -1) {
    integerNum = money
    decimalNum = ''
  } else {
    parts = money.split('.')
    integerNum = parts[0]
    decimalNum = parts[1].substr(0, 4)
  }
  // 获取整型部分转换
  if (parseInt(integerNum, 10) > 0) {
    let zeroCount = 0
    const IntLen = integerNum.length
    for (let i = 0; i < IntLen; i++) {
      const n = integerNum.substr(i, 1)
      const p = IntLen - i - 1
      const q = p / 4
      const m = p % 4
      if (n == '0') {
        zeroCount++
      } else {
        if (zeroCount > 0) {
          chineseStr += cnNums[0]
        }
        // 归零
        zeroCount = 0
        chineseStr += cnNums[parseInt(n)] + cnIntRadice[m]
      }
      if (m == 0 && zeroCount < 4) {
        chineseStr += cnIntUnits[q]
      }
    }
    chineseStr += cnIntLast
  }
  // 小数部分
  if (decimalNum != '') {
    const decLen = decimalNum.length
    for (let i = 0; i < decLen; i++) {
      const n = decimalNum.substr(i, 1)
      if (n != '0') {
        chineseStr += cnNums[Number(n)] + cnDecUnits[i]
      }
    }
  }
  if (chineseStr == '') {
    chineseStr += cnNums[0] + cnIntLast + cnInteger
  } else if (decimalNum == '') {
    chineseStr += cnInteger
  }
  return chineseStr
}
// 获取参数
function GetQueryString(name) {
  var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
  var r = window.location.search.substr(1).match(reg)
  if (r != null) return unescape(r[2])
  return null
}
/*
 * 递归深拷贝
 */
function deepClone(obj) {
  const result = Array.isArray(obj) ? [] : {}
  for (const key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
      if (typeof obj[key] === 'object' && obj[key] !== null) {
        result[key] = deepClone(obj[key])
      } else {
        result[key] = obj[key]
      }
    }
  }
  return result
}
// 当前时间格式化
function getCurrentFormattedTime() {
  const currentDate = new Date()
  const year = currentDate.getFullYear()
  const month = (currentDate.getMonth() + 1).toString().padStart(2, '0')
  const day = currentDate.getDate().toString().padStart(2, '0')
  const hours = currentDate.getHours().toString().padStart(2, '0')
  const minutes = currentDate.getMinutes().toString().padStart(2, '0')
  const seconds = currentDate.getSeconds().toString().padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}
// 当前时间30天时间
function getCurrent30DaysTime(hhmmss = false) {
  const currentDate = new Date()
  const dateAgo = new Date(currentDate.getTime() - 3600 * 1000 * 24 * 30)
  const currentYear = currentDate.getFullYear()
  const currentMonth = (currentDate.getMonth() + 1).toString().padStart(2, '0')
  const currentDay = currentDate.getDate().toString().padStart(2, '0')
  const agoYear = dateAgo.getFullYear()
  const agoMonth = (dateAgo.getMonth() + 1).toString().padStart(2, '0')
  const agotDay = dateAgo.getDate().toString().padStart(2, '0')
  if (hhmmss) {
    return [`${agoYear}-${agoMonth}-${agotDay} 00:00:00`, `${currentYear}-${currentMonth}-${currentDay} 23:59:59`]
  }
  return [`${agoYear}-${agoMonth}-${agotDay}`, `${currentYear}-${currentMonth}-${currentDay}`]
}

/**
 * 数组对象排序
 * @param {*} propertyName  待排序的对象属性
 * @param {*} flag 升序（asc）降序（desc） 默认降序
 * @returns
 */
function creatCompare(propertyName, flag) {
  return function (obj1, obj2) {
    var value1 = obj1[propertyName]
    var value2 = obj2[propertyName]
    if (flag === 'asc') {
      return value1 - value2
    } else {
      return value2 - value1
    }
  }
}

/**
 *
 * @param {*} Name 权限名字  basics_customer_sakesnab
 * @param {*} access 查询的数组
 * @returns
 */
function authoritymanagement(access, name) {
  const arr = access
  const n = name
  if (arr.includes(n)) {
    return true
  } else {
    return false
  }
}
/**
 * 根据值获取label
 * @param {*} arr 需要查询的数组
 * @param {*} val 需要查询的值
 * @param {*} label 显示的值，默认'label'
 * @param {*} value 选中的值，默认'value'
 * @returns
 */
function getVByLabel(arr, val, label = 'label', value = 'value') {
  const tmp = arr.filter(v => v[value] == val)
  return tmp && tmp.length > 0 ? tmp[0][label] : ''
}
// 获取权限信息
function getVpermis(arr, type) {
  arr = arr.filter(v => v.indexOf(type) > -1)
  return arr.map(v => {
    return v ? v.replace(type, '') : ''
  })
}

// 转库位码
function storeCodeForward(code) {
  let str = ''
  if (code) {
    if (code.split('-').length == 5) {
      str = `${code.split('-')[0]}-${code.split('-')[1]}-${code.split('-')[2]}-${code.split('-')[4]}-${code.split('-')[3]}`
    }
  }
  return str
}
/**
 * 电话号码中间四位转成*
 * @param {*} str 需要转成*号的电话号码
 * @returns
 */
function tranPhone(str) {
  let result = ''
  // 判断电话号码是字符串并且非空
  if (str && (typeof str == 'string')) {
    result = str.replace(str.substring(3, 7), '****')
  }
  return result
}
/**
 *  客户姓名中间几位转成*
 * @param {*} str 需要转成*号的姓名
 * @returns
 */
function tranName(str) {
  // 判断客户姓名是字符串并且非空
  if (str && (typeof str == 'string')) {
    let star = '' // 存放名字中间的*
    // 名字为两位时
    if (str.length <= 2) {
      return str.substring(0, 1) + '*'
    } else {
      // 名字长度大于两位
      for (let i = 0; i < str.length - 2; i++) {
        star = star + '*'
      }
      return str.substring(0, 1) + star + str.substring(str.length - 1, str.length)
    }
  }
}

function printHtml(html) {
  let style = getStyle();
  let container = getContainer(html);
  document.body.appendChild(style);
  document.body.appendChild(container);
  getLoadPromise(container).then(() => {
    window.print();
    document.body.removeChild(style);
    document.body.removeChild(container);
  });
}
// 设置打印样式
function getStyle() {
  let styleContent = `
  #print-container {
    display: none;
  }
  @media print {
    body > :not(.print-container) {display: none;}
    html,body {
      margin: 0;
      display: block !important;
      height:auto;
    }
    #print-container {
      display: block;
    }
  }`;
  let style = document.createElement("style");
  style.innerHTML = styleContent;
  return style;
}
// 清空打印内容
function cleanPrint() {
  let div = document.getElementById('print-container')
  if (!!div) { document.querySelector('body').removeChild(div) }
}
// 新建DOM，将需要打印的内容填充到DOM
function getContainer(html) {
  cleanPrint()
  let container = document.createElement("div");
  container.setAttribute("id", "print-container");
  container.innerHTML = html;
  return container;
}
// 图片完全加载后再调用打印方法
function getLoadPromise(dom) {
  let imgs = dom.querySelectorAll("img");
  imgs = [].slice.call(imgs);
  if (imgs.length === 0) return Promise.resolve();
  let finishedCount = 0; return new Promise(resolve => {
    function check() {
      finishedCount++;
      if (finishedCount === imgs.length) { resolve(); }
    }
    imgs.forEach(img => {
      img.addEventListener("load", check);
      img.addEventListener("error", check);
    })
  });
}

function getIndex(index, current, size) {
  return (
    (current - 1) * size + index + 1
  )
}

/**
 * 保留小数精度加减乘除运算
 * @param {*} [0.1, 0.2]
 * @returns 
 */
function addCalc(val) {
  let sum = 0,
    maxDecimalLength = getMaxDecimalLength(val)
  val.forEach((x, index) => {
    sum += Math.round(x * Math.pow(10, maxDecimalLength))
  })
  return sum / Math.pow(10, maxDecimalLength)
}

function getMaxDecimalLength(val) {
  let maxDecimalLength = 0
  val.forEach((x) => {
    const strVal = x.toString(),
      dotIndex = strVal.indexOf('.')
    if (dotIndex > -1) {
      let curDecimalLength = strVal.length - 1 - dotIndex
      if (curDecimalLength > maxDecimalLength) {
        maxDecimalLength = curDecimalLength
      }
    }
  })
  return maxDecimalLength
}

/*
* 减法
* 
*/
function subtractCalc(val) {
  let sum,
    maxDecimalLength = getMaxDecimalLength(val)

  val.forEach((x, index) => {
    let nurVal = Math.round(x * Math.pow(10, maxDecimalLength));

    if (index === 0)
      sum = nurVal
    else
      sum -= nurVal
  })

  return sum / Math.pow(10, maxDecimalLength)
}

/*
* 乘法
* 
*/
function multiplyCalc(val) {
  let sum,
    decimalLengthSum = 0
  val.forEach((x, index) => {
    // 获取当前小数位长度
    let decimalLength = getMaxDecimalLength(x)
    // 将当前数变为整数
    let nurVal = Math.round(x * Math.pow(10, decimalLength));

    decimalLengthSum += decimalLength

    if (index === 0)
      sum = nurVal
    else
      sum *= nurVal
  })
  return sum / Math.pow(10, decimalLengthSum)
}

/*
* 除法
* 
*/
function divideCalc(val) {
  let sum = 0,
    decimalLengthSum = 0
  val.forEach((x, index) => {
    let decimalLength = getMaxDecimalLength(x)
    let nurVal = Math.round(x * Math.pow(10, decimalLength));
    if (index === 0) {
      decimalLengthSum = decimalLength
      sum = nurVal
    } else {
      decimalLengthSum -= decimalLength
      sum /= nurVal
    }
  })
  return sum / Math.pow(10, decimalLengthSum)
}

function sortMethod(str1, str2) {
  let res = 0
  for (let i = 0; ; i++) {
    if (!str1[i] || !str2[i]) {
      res = str1.length - str2.length
      break
    }
    const char1 = str1[i]
    const char1Type = getChartType(char1)
    const char2 = str2[i]
    const char2Type = getChartType(char2)
    // 类型相同的逐个比较字符
    if (char1Type[0] === char2Type[0]) {
      if (char1 === char2) {
        continue
      } else {
        if (char1Type[0] === 'zh') {
          res = char1.localeCompare(char2)
        } else if (char1Type[0] === 'en') {
          res = char1.charCodeAt(0) - char2.charCodeAt(0)
        } else {
          res = char1 - char2
        }
        break
      }
    } else {
      // 类型不同的，直接用返回的数字相减
      res = char1Type[1] - char2Type[1]
      break
    }
  }
  return res
}
function getChartType(char) {
  // 数字（0->9）->大写字母（A->Z）->小写字母（a->z）->中文拼音（a->z）
  if (/^[\u4e00-\u9fa5]$/.test(char)) {
    return ['zh', 300]
  }
  if (/^[a-zA-Z]$/.test(char)) {
    return ['en', 200]
  }
  if (/^[0-9]$/.test(char)) {
    return ['number', 100]
  }
  return ['others', 999]
}
// 防抖函数封装
function debounce(func, delay) {
  let timer = null;
  return function (...args) {
    clearTimeout(timer);
    timer = setTimeout(() => {
      func.apply(this, args);
    }, delay);
  };
}
// 节流函数封装
function throttle(func, delay) {
  let timer = null;
  return function (...args) {
    if (!timer) {
      timer = setTimeout(() => {
        func.apply(this, args);
        timer = null;
      }, delay);
    }
  };
}

export { NoToChinese, convertCurrency, GetQueryString, creatCompare, deepClone, getVByLabel, toParams, getVpermis, authoritymanagement, storeCodeForward, tranPhone, tranName, printHtml, getIndex, addCalc, subtractCalc, multiplyCalc, divideCalc, getCurrentFormattedTime, getCurrent30DaysTime, sortMethod, debounce, throttle }
